package com.uchengwang.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.uchengwang.R;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.utils.DensityUtil;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;


/**
 * @ClassName MultiImageView.java
 * @author shoyu
 * @version 
 * @Description: 显示1~N张图片的View
 */

public class MultiImageView extends LinearLayout {
	private int MAX_WIDTH = 0;

	// 照片的Url列表
	private List<String> imagesList;
	private boolean isVideo = false;

	/**
	 * 长度 单位为Pixel
	 **/
	private int pxOneMaxWandH;  // 单张图最大允许宽高
	private int pxMoreWandH = 0;// 多张图的宽高
	private int pxImagePadding = (int) (AutoUtils.getPercentWidth1px() * 14);// 图片间的间距

	private int MAX_PER_ROW_COUNT = 3;// 每行显示最大数

	private RelativeLayout.LayoutParams onePicPara;
	private LayoutParams morePara, moreParaColumnFirst;
	private LayoutParams rowPara;
	private int allCount;

	private OnItemClickListener mOnItemClickListener;

	public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		mOnItemClickListener = onItemClickListener;
	}

	public MultiImageView(Context context) {
		super(context);
	}

	public MultiImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setList(List<String> lists) throws IllegalArgumentException {
		if (lists == null) {
			throw new IllegalArgumentException("imageList is null...");
		}
		imagesList = lists;
		if (MAX_WIDTH > 0) {
			pxMoreWandH = (MAX_WIDTH - pxImagePadding * 2) / 3; //解决右侧图片和内容对不齐问题
			pxOneMaxWandH = pxMoreWandH * 3/2;
			initImageLayoutParams();
		}

		initView();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (MAX_WIDTH == 0) {
			int width = (int) (DensityUtil.getUtil().getScreenWidth(getContext()) - AutoUtils.getPercentWidth1px() * 52);
			if (width > 0) {
				MAX_WIDTH = width;
				if (imagesList != null && imagesList.size() > 0) {
					setList(imagesList);
				}
			}
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	/**
	 * Determines the width of this view
	 *
	 * @param measureSpec A measureSpec packed into an int
	 * @return The width of the view, honoring constraints from measureSpec
	 */
	private int measureWidth(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		if (specMode == MeasureSpec.EXACTLY) {
			// We were told how big to be
			result = specSize;
		} else {
			// Measure the text
			// result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
			// + getPaddingRight();
			if (specMode == MeasureSpec.AT_MOST) {
				// Respect AT_MOST value if that was what is called for by
				// measureSpec
				result = Math.min(result, specSize);
			}
		}
		return result;
	}

	private void initImageLayoutParams() {
		int wrap = LayoutParams.WRAP_CONTENT;
		int match = LayoutParams.MATCH_PARENT;

//		onePicPara = new LayoutParams(pxOneMaxWandH, pxOneMaxWandH + pxOneMaxWandH * 1 / 3);
		onePicPara = new RelativeLayout.LayoutParams(AutoUtils.getPercentWidthSize(432), AutoUtils.getPercentHeightSize(432));
		moreParaColumnFirst = new LayoutParams(pxMoreWandH, pxMoreWandH);
		morePara = new LayoutParams(pxMoreWandH, pxMoreWandH);
//		morePara.setMargins(pxImagePadding, 0, 0, 0);

		rowPara = new LayoutParams(match, wrap);
	}

	public void setIsVideo(boolean flag) {
		isVideo = flag;
	}

	// 根据imageView的数量初始化不同的View布局,还要为每一个View作点击效果
	private void initView() {
		this.setOrientation(VERTICAL);
		this.removeAllViews();
		if (MAX_WIDTH == 0) {
			//为了触发onMeasure()来测量MultiImageView的最大宽度，MultiImageView的宽设置为match_parent
			addView(new View(getContext()));
			return;
		}

		if (imagesList == null || imagesList.size() == 0) {
			return;
		}

		if (imagesList.size() == 1) {
			addView(createImageView(0, false));
		} else {
			allCount = imagesList.size();//总个数
			if (allCount == 4) {
				MAX_PER_ROW_COUNT = 2;
			} else {
				MAX_PER_ROW_COUNT = 3;
			}
			int rowCount = allCount / MAX_PER_ROW_COUNT
					+ (allCount % MAX_PER_ROW_COUNT > 0 ? 1 : 0);// 行数
			for (int rowCursor = 0; rowCursor < rowCount; rowCursor++) {
				LinearLayout rowLayout = new LinearLayout(getContext());
				rowLayout.setOrientation(LinearLayout.HORIZONTAL);

				rowLayout.setLayoutParams(rowPara);
				if (rowCursor != 0) {
					rowLayout.setPadding(0, 0, 0, 0);
				}

				int columnCount = allCount % MAX_PER_ROW_COUNT == 0 ? MAX_PER_ROW_COUNT
						: allCount % MAX_PER_ROW_COUNT;//每行的列数

				if (rowCursor != rowCount - 1) {
					columnCount = MAX_PER_ROW_COUNT;
				}
				addView(rowLayout);

				int rowOffset = rowCursor * MAX_PER_ROW_COUNT;//角标 行偏移
				for (int columnCursor = 0; columnCursor < columnCount; columnCursor++) {
					int position = columnCursor + rowOffset;
					rowLayout.addView(createImageView(position, true));
				}
			}
		}
	}

	private RelativeLayout createImageView(int position, final boolean isMultiImage) {
		final String url = imagesList.get(position);
		final ImageView imageView = new ColorFilterImageView(getContext());
		if (isMultiImage) {
			imageView.setScaleType(ScaleType.CENTER_CROP);
//			imageView.setLayoutParams(position % MAX_PER_ROW_COUNT == 0 ? moreParaColumnFirst : morePara);
			imageView.setLayoutParams(morePara);
		} else {
			imageView.setAdjustViewBounds(true);
			imageView.setScaleType(ScaleType.CENTER_CROP);
		}
		imageView.setTag(R.id.glide_tag, position);
		imageView.setId(url.hashCode());
		imageView.setOnClickListener(mImageViewOnClickListener);
		if (isMultiImage){
//			int w = AutoUtils.getPercentWidthSize(pxMoreWandH);
			ImageManager.getInstance().loadImage(getContext(), imageView, pxMoreWandH, pxMoreWandH, url, ImageManager.ImageType.ROUND);
		}else {
			if (imgsWidth<1 || imagsHeight <1){
				Glide.with(getContext())
						.load(url)
						.asBitmap()
						.into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {

							@Override
							public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
								// Do something with bitmap here.
								int h = bitmap.getHeight(); //获取bitmap信息，可赋值给外部变量操作，也可在此时行操作。
								int w = bitmap.getWidth();
								if (h > w){
									w = AutoUtils.getPercentWidthSize(288);
									h = AutoUtils.getPercentHeightSize(432);
									onePicPara = new RelativeLayout.LayoutParams(w, h);
								}else if (h <w){
									w = AutoUtils.getPercentWidthSize(432);
									h = AutoUtils.getPercentHeightSize(288);
									onePicPara = new RelativeLayout.LayoutParams(w, h);
								}else {
									w = AutoUtils.getPercentWidthSize(432);
									h = AutoUtils.getPercentHeightSize(432);
									onePicPara = new RelativeLayout.LayoutParams(w, h);
								}
								imageView.setLayoutParams(onePicPara);
								ImageManager.getInstance().loadImage(getContext(), imageView,w, h, url, ImageManager.ImageType.ROUND);

							}

						});
			}else {
				if (imagsHeight > imgsWidth){
					imgsWidth = AutoUtils.getPercentWidthSize(288);
					imagsHeight = AutoUtils.getPercentHeightSize(432);
					onePicPara = new RelativeLayout.LayoutParams(imgsWidth, imagsHeight);
				}else if (imagsHeight <imgsWidth){
					imgsWidth = AutoUtils.getPercentWidthSize(432);
					imagsHeight = AutoUtils.getPercentHeightSize(288);
					onePicPara = new RelativeLayout.LayoutParams(imgsWidth, imagsHeight);
				}else {
					imgsWidth = AutoUtils.getPercentWidthSize(432);
					imagsHeight = AutoUtils.getPercentHeightSize(432);
					onePicPara = new RelativeLayout.LayoutParams(imgsWidth, imagsHeight);
				}
				imageView.setLayoutParams(onePicPara);
				ImageManager.getInstance().loadImage(getContext(), imageView,imgsWidth, imagsHeight, url, ImageManager.ImageType.ROUND);
			}


		}
		RelativeLayout relativeLayout = new RelativeLayout(getContext());
		relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

		if (allCount ==4){
			if (position == 0 || position ==2){//第一,二行最左边偏移为0 以后上传图片数量增加 这里要改动
				relativeLayout.setPadding(0, pxImagePadding, 0, 0);
			}else {
				relativeLayout.setPadding(pxImagePadding, pxImagePadding, 0, 0);
			}

		}else {
			if (position == 0 || position ==3){//第一,二行最左边偏移为0 以后上传图片数量增加 这里要改动
				relativeLayout.setPadding(0, pxImagePadding, 0, 0);
			}else {
				relativeLayout.setPadding(pxImagePadding, pxImagePadding, 0, 0);
			}
		}


		relativeLayout.removeAllViews();
		relativeLayout.addView(imageView);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
		ImageView view = new ImageView(getContext());
		view.setLayoutParams(lp);
		if (isVideo) {
//			view.setImageResource(R.drawable.member_image);
		}
		relativeLayout.addView(view);
		return relativeLayout;
	}

	// 图片点击事件
	private OnClickListener mImageViewOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			if (mOnItemClickListener != null) {
				mOnItemClickListener.onItemClick(view, (Integer) view.getTag(R.id.glide_tag));
			}
		}
	};

	public interface OnItemClickListener {
		public void onItemClick(View view, int position);
	}

	private int imgsWidth, imagsHeight;//单张图片时 图片宽高
	public void setWidthAndHeight(int width, int height){
		imgsWidth = width;
		imagsHeight = height;
	}
}